<template>
  <div>

    <basic-container>

      <div >
        <vue-element-loading :active="isActive" spinner="bar-fade-scale" color="#409eff" background-color="rgba(255,255,255,0.2)"/>
        <el-form :inline="true" :model="formInline" >
          <div style="margin-top: 22px">

            <el-form-item>
              <el-select v-model="formInline.gameTypeId" @change="selectType" clearable placeholder="平台名称">
                <el-option
                  v-for="item in queryData.gameTypeList"
                  :key="item.id"
                  :label="item.typeName"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="formInline.projectId" @change="selectProject" filterable clearable placeholder="游戏">
                <el-option
                  v-for="item in queryData.gameProjectList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="formInline.gameId" @change="selectGame" clearable placeholder="设备">
                <el-option
                  v-for="item in queryData.gameList"
                  :key="item.id"
                  :label="item.gameName +'-'+ item.phoneName"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <!--          <el-form-item>-->
            <!--            <el-select v-model="formInline.serverId" @click.native="selectServer" clearable placeholder="区服名称">-->
            <!--              <el-option-->
            <!--                v-for="item in queryData.gameServerList"-->
            <!--                :key="item.id"-->
            <!--                :label="item.serverName"-->
            <!--                :value="item.id"/>-->
            <!--            </el-select>-->
            <!--          </el-form-item>-->
            <el-form-item v-show="level==2">
              <el-select v-model="formInline.conditionPromote" clearable @change="selectPromoteGroup" filterable placeholder="组长">
                <el-option
                  v-for="item in queryData.promoteGroupList"
                  :key="item.id"
                  :label="item.account"
                  :value="item.id"/>
              </el-select>
            </el-form-item>

            <el-form-item v-show="level == 3">
              <el-select v-model="formInline.promoteId" filterable clearable placeholder="推广员">
                <el-option
                  v-for="item in queryData.promoteList"
                  :key="item.id"
                  :label="item.account"
                  :value="item.id"/>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-date-picker
                v-model="queryData.queryDate"
                type="daterange"
                align="right"
                unlink-panels
                :clearable="false"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>


            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="queryFunc">查询</el-button>
              <el-button type="primary" icon="el-icon-download" @click="downloadReportFunc">下载</el-button>
            </el-form-item>

          </div>
        </el-form>
        <el-table
          :data="gameStatisticsList"
          show-summary
          stripe
          :summary-method="dailyStatisticsListSum"
          ref="el-table"
          style="width: 100%">
          <el-table-column
            prop="data"
            label="账号(姓名)"
            sortable
            key="1">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.account }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userRoleAccount" label="创角数" key="1" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.userRoleAccount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userCount" label="创角用户" key="2" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.userCount }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="newRoleUserValueWithIMEICount" :render-header="renderHeader2" key="3" width="330"
                           label="新创角用户|新创角设备|新创角IP">
            <template slot-scope="scope">
              <span class="skucost-pruice">{{ scope.row.newRoleUserValueWithIMEICount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="actionUserCount" label="登录用户数" key="4" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.actionUserCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="tradeUserCount" label="充值人数" key="5" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.tradeUserCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="rechargeTimes" label="充值次数" key="6" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.rechargeTimes }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" v-if="ischange"  width="150" label="充值总额"
                           key="7">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.totalPrice / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalZsPrice" v-if="ischange" :render-header="renderHeader3" width="180" label="实际充值总额"
                           key="7">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.directCharge / 100 + scope.row.goldPlatValue}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="directCharge" v-if="isshowtrue" key="8" label="现金充值" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.directCharge / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isshowtrue" prop="goldPlatValue" key="9" label="通用币充值" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.goldPlatValue }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isshowtrue" prop="num" key="10" label="绑定币充值" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">0</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isshowtrue" prop="goldDiscountValue" key="11" label="折扣币充值"
                           :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.goldDiscountValue }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isshowtrue" prop="voucherPrice" key="12" label="代金劵使用" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.voucherPrice/100 }}</span>
            </template>
          </el-table-column>

          <el-table-column v-if="level==2" key="12" label="操作" >
            <template slot-scope="scope">
              <a href="#" v-show="userId!= scope.row.userId" @click="viewSubordinatesHandle(scope.row.userId, level+1)"><span class="skucost-pruice" style="color: #1e9fff; text-decoration:underline;">查看下级</span></a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog title="查看下级" :visible.sync="dialogFormViewUser" @close="closeViewUser()"  customClass="customViewUser">
        <div v-if="showViewUser">
          <teamsub :rowDeatils="row" :userIdData="userIdData" :levelData="levelData" :queryData="queryData" :formInline="formInline" ></teamsub>
        </div>
      </el-dialog>

      <div class="block" style="margin-top: 20px;">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </basic-container>
  </div>
</template>

<script>
import {mapGetters} from "vuex";

import tableHeaderTip from '@/components/game/tableHeaderTip';
import addbutton from '@/components/game/addbutton';

import {queryTeamStatistics} from '@/api/statistics/statistics'
import {getpromoterList} from '@/api/system/user'
import moment from "moment";
import user from "@/store/modules/user";
import {gameList, gamePhoneList, gameserverList, gameTypeList} from "@/api/game/game";
import {cloneObj, parseParam} from "@/util/util";
import {getToken} from "@/util/auth";
import VueElementLoading from 'vue-element-loading'
import teamsub from "@/views/statistics/teamsub";
import '@/assets/myicon/iconfont.css'
export default {
  name: "team",
  data() {
    return {
      isActive: false,
      showViewUser:false,
      dialogFormViewUser:false,
      level: user.state.promoteInfo.level,
      userId: user.state.userInfo.userId,
      userIdData:'',
      levelData:'',
      formInline: {
        gameTypeId: '',
        projectId: '',
        gameId: '',
        serverId: '',
        conditionPromote: '',
        promoteId: '',
        startDate: moment().startOf('day').valueOf(),
        endDate: moment().endOf('day').valueOf(),
      },
      page: {
        current: 1,
        size: 10,
        total: 0,
      },
      queryData: {
        gameList: [],
        gameTypeList: [],
        gameServerList: [],
        gameProjectList: [],
        promoteGroupList: [],
        promoteList: [],
        queryDate: [new Date(), new Date()],
        queryDateStr:[],
      },
      gameStatisticsList: [],
      date: '',
      checked: false,
      tabPositionThird: 'userRoleAccount',
      isshowtrue: false,
      ischange: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

    }

  },
  components: {
    addbutton,
    teamsub,
    VueElementLoading
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },

  mounted() {

    console.log('this.$route.query.userId',this.$route.query.userId)
    this.initQueryDataList()
    this.queryGameStatisticsFunc()
  },


  methods: {


    /**
     * 下载报表
     */
    downloadReportFunc() {

      let formData = cloneObj(this.formInline);
      if (this.checked) {
        formData.promoteId = user.state.userInfo.userId
      }
      formData.startDate = moment(this.queryData.queryDate[0].getTime()).startOf('day').valueOf()
      formData.endDate = moment(this.queryData.queryDate[1].getTime()).endOf('day').valueOf()
      window.location.href = `/api/blade-statistic/statistics/queryTeamStatisticsReport?${parseParam(formData)}&blade-auth=${getToken()}`
    },

    /**
     * 查看下级
     */
    // viewSubordinatesHandle(userIdData, levelData) {
    //   this.queryData.queryDateStr[0] = JSON.stringify(this.queryData.queryDate[0])
    //   this.queryData.queryDateStr[1] = JSON.stringify(this.queryData.queryDate[1])
    //   this.$router.push({name:"查看下级", path:"/statistics/teamsub", query:{userId:userIdData, level:levelData, queryData:this.queryData, formInline:this.formInline }})
    // },
    viewSubordinatesHandle(userIdData, levelData) {
      // this.$router.push({name: '查看角色', path: '/role/index', query: {id: row.id}});
      this.showViewUser = false
      this.dialogFormViewUser = true
      this.showViewUser = true
      this.userIdData= userIdData,
        this.levelData=levelData
    },
    closeViewUser(){
      this.showViewUser = false
      this.dialogFormViewUser = false
      this.row={}
    },
    /**
     * 搜索条件初始化
     */
    initQueryDataList() {
      this.isActive = true
      if (this.level === 2) {
        this.getPromoteGroupList(this.userId)
      } else if (this.level === 3) {
        this.getPromoteList(this.userId)
      }
      this.gameTypeList()
      this.getProjectList()
      this.getGameList()
    },

    /**
     * 搜索按钮
     */
    queryFunc() {
      this.refreshTable()
    },

    dailyStatisticsListSum(param) {

      const {columns, data} = param;

      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => item[column.property]);
        if (values.length != 0) {
          if (column.property === 'newRoleUserValueWithIMEICount') {
            sums[index] = values.reduce((prev, curr) => {
              if (prev === 0) {
                return curr
              }
              let prevArr = prev.split("|")
              let currArr = curr.split("|")
              return (Number(prevArr[0]) + Number(currArr[0])) + "|"
                + (Number(prevArr[1]) + Number(currArr[1])) + "|" + (Number(prevArr[2]) + Number(currArr[2]))
            })
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            })

          }
        }

        if (sums[index] === 0) {
          sums[index] = "--"
        } else if(index == 8) {
          let sumE = 0;
          for(let i = 0; i < this.gameStatisticsList.length; i++) {
            sumE += this.gameStatisticsList[i].directCharge / 100 + this.gameStatisticsList[i].goldPlatValue
          }
          sums[8] = sumE;
        } else if (column.property === "totalPrice" || column.property === "directCharge" || column.property === "voucherPrice") {
          sums[index] = sums[index] / 100
        }
      });

      return sums;
    },

    refreshTable() {
      this.isActive = true
      this.queryGameStatisticsFunc()
    },

    queryGameStatisticsFunc() {
      let formData = cloneObj(this.formInline);
      if(this.checked) {
        formData.promoteId = this.userId
      }

      formData.startDate = moment(this.queryData.queryDate[0].getTime()).startOf('day').valueOf()
      formData.endDate = moment(this.queryData.queryDate[1].getTime()).endOf('day').valueOf()
      queryTeamStatistics(formData, this.page.current, this.page.size).then(res => {
        this.isActive = false
        let data = res.data.data
        this.gameStatisticsList = data.records
        this.page.total = data.total
      })
    },

    fatherMethod() {
      this.isshowtrue ? this.isshowtrue = false : this.isshowtrue = true;
      this.ischange = false;
      this.$nextTick(() => {

        this.ischange = true;
        this.$refs['el-table'].doLayout();
      })

    },
    renderHeader2(h, {column}) {
      return h(  // 创建元素
        'div', [
          h('span', column.label),  // label标题文案
          h(tableHeaderTip, {  // tooltips组件
            props: {
              messages: ['新创角用户：当日(24小时),首次创建角色的用户数;', '新创角设备：当日(24小时),首次创建角色设备总数(去重);', '新创角设备：当日(24小时),首次创建角色设备总数(去重);'],
            }
          })
        ]
      )
    },

    renderHeader3(h, {column}) {
      return h(  // 创建元素
        'div', [
          h('span', column.label),  // label标题文案
          h(addbutton, {  // tooltips组件
            props: {
              messages: ['实际充值总额'],
              isshowtrue: this.isshowtrue,
            }
          })
        ]
      )
    },
    handleSizeChange(val) {
      this.page.size = val
      this.refreshTable()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.refreshTable()
    },

    renderHeader(h, {column}) {
      let label = column.label
      let txtmap = {
        '创角数': '创角数：当日(24小时),成功创建角色数量(唯一,含滚服用户)',
        '创角用户': '创角用户：当日(24小时),成功创角的用户数(去重,含滚服用户)',
        '新创角用户|新创角设备|新创角IP': '新创角用户：当日(24小时),首次创建角色的用户数;' +
          '新创角设备：当日(24小时),首次创建角色设备总数(去重);' +
          '新创角IP：当日(24小时),首次创建角色IP总数(去重);',
        '登录用户数': '登录用户数：当日(24小时),登录的用户数(去重)',
        '充值人数': '充值人数：当日(24小时),在游戏内充值成功的订单的用户数(去重)',
        '充值次数': '充值次数：当日(24小时),在游戏内充值成功的订单数量',
        '充值总额': '充值总额：当日(24小时),在游戏内充值成功的订单金额总和',
        '现金充值': '现金充值：当日(24小时),在游戏内充值成功的订单,使用现金支付金额总和',
        '通用币充值': '通用币充值：当日(24小时),在游戏内充值成功的订单,使用通用币支付金额总和',
        '绑定币充值': '绑定币充值：当日(24小时),在游戏内充值成功的订单,使用绑定币支付金额总和',
        '折扣币充值': '折扣币充值：当日(24小时),在游戏内充值成功的订单,使用折扣币支付金额总和,该部分不参与结算',
        '代金劵使用': '代金劵使用：当日(24小时),在游戏内充值成功的订单,使用代金券金额总和,该部分不参与结算',
      }
      return h('span', {}, [
        h('span', {}, label),
        h('el-popover', {
          props: {
            placement: 'top-start', 'data-html': 'true', trigger: 'hover', content: (function () {
              return txtmap[label];
            })()
          }
        }, [
          h('i', {slot: 'reference',class: 'iconfont el-third-iconwenhao',style:'margin-left:2px' }, '')
        ]),

      ])
    },


    selectType() {
      this.formInline.projectId = ''
      this.formInline.gameId = ''
      this.formInline.serverId = ''
      this.getProjectList()
      this.getGameList()
    },

    selectProject() {
      this.formInline.gameId = ''
      this.formInline.serverId = ''
      this.getGameList()
    },
    selectGame() {
      this.formInline.serverId = ''
    },

    selectServer() {
      if (this.formInline.gameId !== '' || this.formInline.projectId !== '') {
        this.getGameServerList()
      }else {
        this.queryData.gameServerList = []
        this.$message({
          type: "error",
          message: "请先选择游戏"
        });
      }
    },

    selectPromoteGroup(value) {
      this.formInline.promoteId = ''
      if (value === '') {
        this.queryData.promoteList = []
        return
      }
      this.getPromoteList(this.formInline.conditionPromote)
    },


    getPromoteGroupList(pid) {
      getpromoterList({"userPid": pid, "level": 3}).then(res => {
        this.queryData.promoteGroupList = res.data.data;
      });
    },

    getPromoteList(pid) {
      getpromoterList({"userPid": pid, "level": 4}).then(res => {
        this.queryData.promoteList = res.data.data
      });
    },

    getGameServerList() {
      gameserverList(this.formInline).then(res => {
        this.queryData.gameServerList = res.data.data
      });
    },
    getGameList() {
      gamePhoneList(this.formInline).then(res => {
        this.queryData.gameList = res.data.data
      });
    },
    getProjectList() {
      gameList({"typeId": this.formInline.gameTypeId}).then(res => {
        this.queryData.gameProjectList = res.data.data
      });
    },

    gameTypeList() {
      gameTypeList().then(res => {
        this.queryData.gameTypeList = res.data.data
      });

    },
  }

}
</script>

<style>
.customViewUser{
  width: 80%;
  background-color: #FFFFFF !important;
}
</style>
